<template>
  <div class="container">
    <div class="row">
      <div class="col-6">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">项目</h3>
          </div>
          <div class="card-body">
            <ProjectTableWidget @select="handleSelect" />
          </div>
        </div>
      </div>
      <div class="col-6">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">{{ selectedProject.name }} 绑定仓库</h3>

            <div class="card-toolbar">
              <a href="javascript:void(0)" @click="onToolButtonClick">
                <i class="fa fa-plus text-primary" />
                添加仓库
              </a>
            </div>
          </div>
          <div class="card-body">
            <RepositoryListWidget :repositories="repositories" @delete-repo="handleDeleteRepo" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="showDialog" title="添加仓库关联" width="30%">
    <RepoSelect v-model="selectedRepo" />
    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import ProjectTableWidget from '@/components/biz/ProjectTableWidget.vue';
import type { Project } from '@/types/business/project';
import { ref } from 'vue';
import { projectService } from '@/services/business/project.service';
import RepositoryListWidget from '@/components/biz/RepositoryListWidget.vue';
import type { RepositorySummary } from '@/types/business/project';
import RepoSelect from '@/components/common/RepoSelect.vue';
import { ElMessage } from 'element-plus';
import type { RepoValue } from '@/types/business/repository';

const repositories = ref<RepositorySummary[]>([]);
const selectedProject = ref<Project>({} as Project);
const showDialog = ref(false);
const selectedRepo = ref<RepoValue | null>(null);

const handleSelect = async (project: Project) => {
  const res = await projectService.getRepositoryNames(project.id);
  repositories.value = res;
  selectedProject.value = project;
};

const onToolButtonClick = () => {
  showDialog.value = true;
};

const handleConfirm = async () => {
  if (!selectedRepo.value || !selectedProject.value.id) return;
  await projectService.addRepository(selectedProject.value.id, selectedRepo.value.id);
  ElMessage.success('关联添加成功');
  const res = await projectService.getRepositoryNames(selectedProject.value.id);
  repositories.value = res;
  showDialog.value = false;
  selectedRepo.value = null;
};

const handleDeleteRepo = (projectRepoId: string) => {
  const idx = repositories.value.findIndex((repo) => repo.id === projectRepoId);
  if (idx !== -1) {
    repositories.value.splice(idx, 1);
  }
};
</script>
